package com.hunttown.mes.manage.service;

import com.hunttown.mes.common.keys.KeyConstants;
import com.hunttown.mes.common.cache.Cache;
import com.hunttown.mes.common.utils.FormatUtils;
import com.hunttown.common.domain.Page;
import com.hunttown.mes.common.utils.StringUtils;
import com.hunttown.mes.rpc.api.TransportDepartmentRpcService;
import com.hunttown.mes.rpc.domain.TransportDepartmentDTO;
import com.hunttown.mes.rpc.domain.query.TransportDepartmentDTOQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * created by wangjunfu on 2019-04-28 16:29:01
 */
@Service
public class TransportDepartmentManageService {

    private final static Logger logger = LoggerFactory.getLogger(TransportDepartmentManageService.class);

    private final TransportDepartmentRpcService rpcService;
    private final Cache jedisCache;

    @Autowired
    public TransportDepartmentManageService(TransportDepartmentRpcService rpcService, Cache jedisCache) {
        this.rpcService = rpcService;
        this.jedisCache = jedisCache;
    }

    // 新增
    public TransportDepartmentDTO insert(TransportDepartmentDTO objDTO) {
        return rpcService.insert(objDTO);
    }

    // 通过ID修改
    public Boolean updateInfoById(TransportDepartmentDTO objDTO) {
        Boolean isNext = rpcService.updateInfoById(objDTO);
        if (isNext) {
            // 刷新部门缓存
            refreshStaffCacheAll(objDTO.getId());
        }

        return isNext;
    }

    // 通过Query修改
    public Boolean updateInfoByQuery(TransportDepartmentDTOQuery objDTOQuery) {
        Boolean isNext = rpcService.updateInfoByQuery(objDTOQuery);

        //批量更新
        if (isNext && objDTOQuery.getIds() != null) {
            // 刷新部门缓存
            List<Integer> list = new ArrayList<>();
            try {
                list = (List<Integer>) objDTOQuery.getIds();
            } catch (Exception e) {
                e.printStackTrace();
            }
            refreshStaffCacheByIdList(list);
        }

        return isNext;
    }

    // 通过ID删除
    public Boolean delete(Integer id) {
        Boolean isNext = rpcService.deleteById(id);
        if (isNext) {
            // 刷新部门缓存
            refreshStaffCacheAll(id);
        }
        return isNext;
    }

    // 批量删除
    public Boolean deleteForBatch(String clearIds) {

        //处理 “,5,6,7,” 为List
        List<Integer> idList = FormatUtils.commaToList_Integer(clearIds);

        if (idList.size() == 0) {
            return false;
        }

        TransportDepartmentDTOQuery query = new TransportDepartmentDTOQuery();
        query.setDeleteFlag(1);
        query.setIds(idList);

        Boolean isNext = rpcService.updateInfoByQuery(query);
        if (isNext) {
            // 刷新部门缓存
            refreshStaffCacheByIdList(idList);
        }

        return isNext;
    }

    // 通过ID获取
    public TransportDepartmentDTO getById(Integer id) {
        if (id <= 0) {
            return null;
        }
        return rpcService.selectById(id);
    }

    // 通过Query获取
    public TransportDepartmentDTO getByQuery(TransportDepartmentDTOQuery objDTOQuery) {
        return rpcService.selectObjByQuery(objDTOQuery);
    }

    // 获取分页列表
    public Page<TransportDepartmentDTO> getForPage(TransportDepartmentDTOQuery objDTOQuery) {
        return rpcService.getListForPage(objDTOQuery);
    }

    // 获取所有部门列表
    public List<TransportDepartmentDTO> getForList() {
        TransportDepartmentDTOQuery query = new TransportDepartmentDTOQuery();
        query.setStopFlag(0);
        query.setPageSize(1000);
        Page<TransportDepartmentDTO> deplist = getForPage(query);
        return getListByRecursion(deplist.getItems(), 0, "|");
    }

    // 改变某条记录的使用状态
    public Boolean changeState(Integer id, Integer state) {
        TransportDepartmentDTO obj = new TransportDepartmentDTO();
        obj.setStopFlag(state);
        obj.setId(id);
        return updateInfoById(obj);
    }

    public TransportDepartmentDTO getByDepname(String depname) {
        TransportDepartmentDTOQuery query = new TransportDepartmentDTOQuery();
        query.setDepNameCn(depname);
        query.setStopFlag(0);
        return getByQuery(query);
    }

    /**
     * 通过ID，从缓存中获取
     *
     * @param id 部门ID
     * @return
     */
    public TransportDepartmentDTO getFromCacheId(Integer id) {
        if (id == null || id <= 0) {
            return null;
        }

        TransportDepartmentDTO obj = jedisCache.oget(KeyConstants.DEPARTMENT_INFO_CACHE_KEY_ID + id, TransportDepartmentDTO.class);
        if (obj == null) {
            obj = getById(Integer.valueOf(id));
            if (obj != null) {
                jedisCache.oset(KeyConstants.DEPARTMENT_INFO_CACHE_KEY_ID + id, obj);
            }
        }

        return obj;
    }

    //region 刷新部门缓存

    /**
     * 通过部门id刷部门缓存
     *
     * @param id
     */
    private void refreshStaffCacheAll(Integer id) {
        if (id == null || id <= 0) {
            return;
        }

        TransportDepartmentDTO obj = getById(id);
        if (obj != null) {
            jedisCache.delete(KeyConstants.DEPARTMENT_INFO_CACHE_KEY_ID + id);
        }
    }

    /**
     * 通过部门id刷部门缓存(批量)
     *
     * @param idList
     */
    private void refreshStaffCacheByIdList(List<Integer> idList) {
        if (idList == null || idList.size() == 0) {
            return;
        }

        for (Integer id : idList) {
            refreshStaffCacheAll(id);
        }
    }

    //endregion

    /**
     * 获取部门名称
     *
     * @param id 部门id
     * @return
     */
    public String getDepName(Integer id) {
        String depname = "--";

        TransportDepartmentDTO dto = getFromCacheId(Integer.valueOf(id.toString()));
        if (dto == null) {
            dto = getById(id);
        }

        if (dto != null) {
            depname = dto.getDepNameCn();
        }

        return depname;
    }

    /**
     * 通过递归得到树形结构
     *
     * @param list      部门列表
     * @param parentId  父ID
     * @param splitMark 标识符
     * @return
     */
    public List<TransportDepartmentDTO> getListByRecursion(List<TransportDepartmentDTO> list, Integer parentId, String splitMark) {
        List<TransportDepartmentDTO> returnList = new ArrayList<>();

        if (parentId > 0) {
            splitMark += "┄";
        }

        if (list != null && list.size() > 0) {
            List<TransportDepartmentDTO> mainList = list.stream().filter(s -> s.getParentId().equals(parentId)).collect(Collectors.toList());

            for (TransportDepartmentDTO item : mainList) {
                if (parentId > 0) {
                    item.setDepNameCn(String.format("%s %s", splitMark, item.getDepNameCn()));
                }
                returnList.add(item);

                List<TransportDepartmentDTO> next_list = getListByRecursion(list, item.getId(), splitMark);
                for (TransportDepartmentDTO item_child : next_list) {
                    returnList.add(item_child);
                }
            }
        }

        return returnList;
    }

    /**
     * 通过递归获取当前部门名称及上的上级名称
     * 格式：京东集团>京东零售>数据中台 ...
     *
     * @param id      部门ID
     * @param depName 部门名称
     * @return
     */
    public String getRootNameByRecursion(Integer id, String depName) {
        if (id <= 0) {
            return depName;
        }

        TransportDepartmentDTO obj = getById(id);

        if (StringUtils.isBlank(depName) && obj != null) {
            depName = obj.getDepNameCn();
            obj = getById(obj.getParentId());
        }

        if (obj != null) {
            depName = String.format("%s-%s", obj.getDepNameCn(), depName);
            if (obj.getParentId() > 0) {
                depName = getRootNameByRecursion(obj.getParentId(), depName);
            }
        }

        return depName;
    }

    /**
     * 通过递归获取当前对象的最顶级ID
     *
     * @param id 部门ID
     * @return 顶级部门ID
     */
    public Integer getRootIdByRecursion(Integer id) {
        if (id <= 0) {
            return id;
        }

        Integer result = id;

        TransportDepartmentDTO obj = getById(id);

        if (obj.getParentId() > 0) {
            result = getRootIdByRecursion(obj.getParentId());
        } else {
            result = obj.getId();
        }

        return result;
    }

    /**
     * 通过递归获取当前id 数据及他所有子分类数据
     * 返回 List 对象
     *
     * @param id          部门ID
     * @param needGetCurr 是否获取当前id 的数据
     * @return
     */
    public List<TransportDepartmentDTO> getChildListById(Integer id, boolean needGetCurr) {
        List<TransportDepartmentDTO> returnList = new ArrayList<>();

        if (id <= 0) {
            return returnList;
        }

        // 获取当前id 的数据
        if (needGetCurr) {
            TransportDepartmentDTO obj = getById(id);
            if (obj != null) {
                returnList.add(obj);
            }
        }

        TransportDepartmentDTOQuery query = new TransportDepartmentDTOQuery();
        query.setParentId(id);
        query.setStopFlag(0);
        query.setPageSize(1000);

        Page<TransportDepartmentDTO> list = getForPage(query);

        if (list != null && list.getItems().size() > 0) {
            for (TransportDepartmentDTO item : list.getItems()) {
                returnList.add(item);

                List<TransportDepartmentDTO> next_list = getChildListById(item.getId(), false);
                returnList.addAll(next_list);
            }
        }

        return returnList;
    }

    /**
     * 通过递归获取当前id 数据及他所有子分类id
     * 返回 List id
     *
     * @param id 部门ID
     * @return
     */
    public List<Integer> getChildIdsByRecursion(Integer id) {
        List<Integer> idList = new ArrayList<>();
        idList.add(id);

        TransportDepartmentDTOQuery query = new TransportDepartmentDTOQuery();
        query.setParentId(id);
        query.setStopFlag(0);
        query.setPageSize(1000);

        Page<TransportDepartmentDTO> childList = getForPage(query);
        if (childList != null && childList.getItems().size() > 0) {
            for (TransportDepartmentDTO item : childList.getItems()) {
                List<Integer> next_list = getChildIdsByRecursion(item.getId());
                idList.addAll(next_list);
            }
        }

        return idList;
    }
}